/**
 * 
 */
package com.android.gtdroid;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;

/**
 * @author xiang
 *
 */
public class SearchAct extends ListActivity {
	
	private final String[] fromCols = new String[] {
			"item_name",
			"item_context",
			"item_pos",
			"item_tags"};
	private final int[] toLayouts = new int[] {
			R.id.tv_task,
			R.id.tv_row_context,
			R.id.tv_row_pos,
			R.id.tv_row_tag};
	private final String TAG = "SearchAct";
	
	private GTDApp mGA;
	private ExpandableListView mElv;
	private MySimpleExpandableListAdapter mMsela;
	private ArrayList<HashMap<String, Object>> groups = new ArrayList<HashMap<String, Object>>();
	private ArrayList<ArrayList<HashMap<String, Object>>> children =
			new ArrayList<ArrayList<HashMap<String, Object>>>();
	private int mSearchResult = 0;
	private TextView mTvResult;
	private String queryString;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.panel_search);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tb_search);
		
		initViews();
		
		mGA = (GTDApp) getApplication();
		
		mMsela = new MySimpleExpandableListAdapter(
				this,
				C.ADAPTER.SEARCH,
				groups,
				R.layout.grp_search,
				new String[] { "item_list", "list_count" },
				new int[] { R.id.tv_search_group, R.id.tv_search_count },
				children, R.layout.row_task,
				fromCols,
				toLayouts);
		mElv.setAdapter(mMsela);
		
//		onSearchRequested();
		
		handleIntent(getIntent());
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		
		setIntent(intent);
		handleIntent(intent);
	}
	
	private void handleIntent(Intent intent) {
		// TODO Auto-generated method stub
		final String queryAction = intent.getAction();
		if (Intent.ACTION_SEARCH.equals(queryAction)) {
			String query = intent.getStringExtra(SearchManager.QUERY).trim();
			saveSearchHistory(query);
			
			updateAdapterData(intent);
			
			mTvResult.setText("\'"+queryString+"\' 的搜索结果共 "+mSearchResult+" 条");
//			Toast.makeText(MainAct.this, query, Toast.LENGTH_LONG).show();
		}
	}
	
	private void saveSearchHistory(String query) {
		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
				MySuggestionsProvider.AUTHORITY,
				MySuggestionsProvider.MODE);
		suggestions.saveRecentQuery(query, null);
	}
	
	private void clearSearchHistory() {
		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
				MySuggestionsProvider.AUTHORITY,
				MySuggestionsProvider.MODE);
		suggestions.clearHistory();
	}

	private void initViews() {
		mElv = (ExpandableListView) findViewById(android.R.id.list);
		mElv.setGroupIndicator(null);
		mElv.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				
				HashMap<String, Object> hmSelected = (HashMap<String, Object>) children
						.get(groupPosition).get(childPosition);
				
				long posInTable = (Long) hmSelected.get("item_id");
				int taskStatus = (Integer) hmSelected.get("item_status");
				String list = (String) hmSelected.get("item_list");
				int listIndex = mGA.lists.indexOf(list);
				
				/*if (taskStatus != C.TASK.UNCOMPLETED) {
					String list = (String) hmSelected.get("item_list");
					listIndex = ga.lists.indexOf(list);
				}
				Log.e(tag, "listIndex is: "+listIndex);*/
				
				Intent itt = new Intent(SearchAct.this, TaskDetailAct.class);
				
				itt.putExtra("row_id", posInTable);
				itt.putExtra("selected_task", hmSelected);
				itt.putExtra("list_index", listIndex);
				itt.putExtra("task_status", taskStatus);
				
				startActivity(itt);
				
				return false;
			}
		});
		
		mTvResult = (TextView) findViewById(R.id.tv_search);
		
		Button btn_search_back = (Button) findViewById(R.id.btn_search_back);
		btn_search_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SearchAct.this.finish();
			}
		});
	}

	
	/*private void getHashArray(Cursor cursor, ArrayList<HashMap<String,Object>> items) {
		HashMap<String, Object> hm;
		
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			long rowId = cursor.getLong(DBTaskAdapter.COL_ID);
			String task = cursor.getString(DBTaskAdapter.COL_TASK_NAME);
			String note = cursor.getString(DBTaskAdapter.COL_TASK_NOTE);
			String list = cursor.getString(DBTaskAdapter.COL_TASK_LIST);
			
			String ctt = cursor.getString(DBTaskAdapter.COL_TASK_CONTEXT);
			String prj = cursor.getString(DBTaskAdapter.COL_TASK_PROJECT);
			String pos = cursor.getString(DBTaskAdapter.COL_TASK_POS);
			
			int status = cursor.getInt(DBTaskAdapter.COL_TASK_STATUS);
			String st = cursor.getString(DBTaskAdapter.COL_TASK_ST);
			String et = cursor.getString(DBTaskAdapter.COL_TASK_ET);
			String repeat = cursor.getString(DBTaskAdapter.COL_TASK_REPEAT);
			String remind = cursor.getString(DBTaskAdapter.COL_TASK_REMIND);
			
			String prior = cursor.getString(DBTaskAdapter.COL_TASK_PRIOR);
			String tags = cursor.getString(DBTaskAdapter.COL_TASK_TAG);
			String created = cursor.getString(DBTaskAdapter.COL_TASK_CREATED);
			int completed = cursor.getInt(DBTaskAdapter.COL_TASK_COMPLETED);
			
			hm = new HashMap<String, Object>();
			hm.put("item_id", rowId);
			hm.put("item_name", task);
			hm.put("item_note", note);
			hm.put("item_list", list);
			
			hm.put("item_context", ctt);
			hm.put("item_project", prj);
			hm.put("item_pos", pos);
			
			hm.put("item_status", status);
			hm.put("item_st", st);
			hm.put("item_et", et);
			hm.put("item_repeat", repeat);
			hm.put("item_remind", remind);
			
			hm.put("item_prior", prior);
			hm.put("item_tags", tags);
			hm.put("item_created", created);
			hm.put("item_completed", completed);
			
			items.add(hm);
		}
	}*/
	
	private void updateAdapterData(Intent intent) {
		queryString = intent.getStringExtra(SearchManager.QUERY).trim();
		
		HashMap<String, Object> hm;
		String query;
		
		groups.clear();
		for (int i=0; i<children.size(); i++)
			children.get(i).clear();
		children.clear();
		
		// get number of each task list
		query = "select task_list, count(_id) from " + mGA.getDbta().getTableName()
				+ " where task_name like \'%" + queryString + "%\'"
				+ " or task_note like \'%" + queryString + "%\'"
				+ " group by task_list";
		Cursor listCursor = mGA.getDbta().excuteSQL(query);
		
		Log.e(TAG , "number of groups: "+listCursor.getCount());
		
		if (listCursor.moveToFirst()) {
			do {
				String listName = listCursor.getString(0);
				int listCount = listCursor.getInt(1);
				
				hm = new HashMap<String, Object>();
				hm.put("item_list", listName);
				hm.put("list_count", (new Integer(listCount)).toString());
				
				groups.add(hm);
			} while (listCursor.moveToNext());
		}
		for (int i=0; i<groups.size(); i++) {
			children.add(new ArrayList<HashMap<String,Object>>());
		}

		// get selected tasks
		query = "select * from " + mGA.getDbta().getTableName()
				+ " where task_name like \'%" + queryString + "%\'"
				+ " or task_note like \'%" + queryString + "%\'"
				+ " order by task_created desc";
		Cursor taskCursor = mGA.getDbta().excuteSQL(query);
		
		for (taskCursor.moveToFirst(); !taskCursor.isAfterLast(); taskCursor.moveToNext()) {
			mSearchResult++;
			
			long rowId = taskCursor.getLong(DBTaskAdapter.COL_ID);
			String task = taskCursor.getString(DBTaskAdapter.COL_TASK_NAME);
			String note = taskCursor.getString(DBTaskAdapter.COL_TASK_NOTE);
			String listName = taskCursor.getString(DBTaskAdapter.COL_TASK_LIST);
			String ctt = taskCursor.getString(DBTaskAdapter.COL_TASK_CONTEXT);
			String prj = taskCursor.getString(DBTaskAdapter.COL_TASK_PROJECT);
			String pos = taskCursor.getString(DBTaskAdapter.COL_TASK_POS);
			int status = taskCursor.getInt(DBTaskAdapter.COL_TASK_STATUS);
			String st = taskCursor.getString(DBTaskAdapter.COL_TASK_ST);
			String et = taskCursor.getString(DBTaskAdapter.COL_TASK_ET);
			String repeat = taskCursor.getString(DBTaskAdapter.COL_TASK_REPEAT);
			String remind = taskCursor.getString(DBTaskAdapter.COL_TASK_REMIND);
			String prior = taskCursor.getString(DBTaskAdapter.COL_TASK_PRIOR);
			String tags = taskCursor.getString(DBTaskAdapter.COL_TASK_TAG);
			String created = taskCursor.getString(DBTaskAdapter.COL_TASK_CREATED);
			int completed = taskCursor.getInt(DBTaskAdapter.COL_TASK_COMPLETED);
			
			hm = new HashMap<String, Object>();
			hm.put("item_id", rowId);
			hm.put("item_name", task);
			hm.put("item_note", note);
			hm.put("item_list", listName);
			
			hm.put("item_context", ctt);
			hm.put("item_project", prj);
			hm.put("item_pos", pos);
			
			hm.put("item_status", status);
			hm.put("item_st", st);
			hm.put("item_et", et);
			hm.put("item_repeat", repeat);
			hm.put("item_remind", remind);
			
			hm.put("item_prior", prior);
			hm.put("item_tags", tags);
			hm.put("item_created", created);
			hm.put("item_completed", completed);
			
			int grpIndex = 0;
			for (int j=0; j<groups.size(); j++) {
				if (listName.equals(groups.get(j).get("item_list"))) {
					grpIndex = j;
					break;
				}
			}
			
			children.get(grpIndex).add(hm);
		}
		
		for (int i=0; i<groups.size(); i++)
			mElv.expandGroup(i);
		
		mMsela.notifyDataSetChanged();
	}
	
	@Override
	public boolean onSearchRequested() {
		// TODO Auto-generated method stub
		return super.onSearchRequested();
	}
	
}
